<!--
* description: 领用出库
* author: chenweilin
* createdDate: 2021/7/15
-->
<template>
  <div class="app-container app-container-table">
    <div class="formBoxContain">
      <one-table-template
        ref="multipleTable"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-form-fields="formField"
        :dynamic-table-cols="tableCols"
        :dynamic-table-defult-height="350"
        :dynamic-is-show-select="true"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-init-table="false"
        :is-show-pagination="false"
        :callback-obj="callbackObj"
      >
        <template #outStoreQty="scope">
          <el-input-number
            :key="'qty' + scope.$index"
            v-model="scope.row['outStoreQty']"
            :step="1"
            :min="0"
            :max="scope.row['availableInventory']"
            step-strictly
          />
        </template>
      </one-table-template>
      <Add
        ref="addcollect"
        :dynamic-edit-row-data="editRowData"
        :chosenList="chosenList"
        @selectiondata="selectiondata1"
      />
    </div>
  </div>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/vehicleManagement'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
import { exportExcel } from '@/utils/getTimeString.js'
import { formMixins } from '@/components/mixins/formMixins'

export default {
  components: {
    dialogHeader,
    OneTableTemplate,
    Add: () => import('@/views/pa/branchWarehouseManagement/otherdeliveryapplication/add.vue')
  },
  // 组件混入对象
  mixins: [formMixins],
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      chosenList: [],
      EditRowData:{},
      editRowData:{},
      dynamicApiConfigs: '',
      isViewPopWindowsAdd: false,
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // {
            //   compKey: 'compKey10',
            //   labelName: '领用去向：',
            //   codeField: 'applyDept',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true,
            //   span: 6,
            //   isRequire: true
            // },
            // {
            //   compKey: 'compKey20',
            //   labelName: '成本中心:',
            //   codeField: 'costCentre',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMust: true,
            //   span: 6,
            //   isRequire: true
            // },
            {
              compKey: 'compKey30',
              labelName: '申请人：',
              codeField: 'applyPerson',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              isRequire: true
            },
            // {
            //   compKey: 'compKey40',
            //   labelName: '出库用途：',
            //   codeField: 'applyUse',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true,
            //   isRequire: true
            // },
            {
              compKey: 'compKey50',
              labelName: '收货人:',
              codeField: 'receivePerson',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6,
              isRequire: true
            },
            // {
            //   compKey: 'compKey60',
            //   labelName: '联系电话:',
            //   codeField: 'linkPhone',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMust: true,
            //   span: 6,
            //   isRequire: true,
            //   validrule: {
            //     isPhone: true,
            //     maxlength: 11
            //   }
            // },
            // {
            //   compKey: 'compKey70',
            //   labelName: '收货地址:',
            //   codeField: 'receiveAddress',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMust: true,
            //   span: 12,
            //   isRequire: true
            // }
            // {
            //   compKey: 'compKey80',
            //   labelName: '出库仓库：',
            //   codeField: 'warehouseName',
            //   component: () => import('@/components/org/commonSelect'),
            //   oFields: 'warehouseName,warehouseName',
            //   customObj: {
            //     api: {
            //       APIUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryWarehouseName.do'
            //     },
            //     listQuery: {},
            //     selectType: '1'
            //   },
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: true,
            //   isRequire: true
            // }
          ],
      formField: this.$utils.getFormField(this, {
        outboundType: '4',
        outboundTypeCn: '',
        applyDept: '',
        costCentre: '',
        applyPerson: '',
        applyUse: '',
        receivePerson: '',
        linkPhone: '',
        receiveAddress: '',
        warehouseName: ''
      }),
      // 标题
      textMap: {
        edit: '查看出库编辑',
        add: '查看出库新增',
        look: '查看出库明细'
      },
      selectiondata: [],
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        onRowClick: (currentRow) => {
          // this.onRightRowClick(currentRow);
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
          console.log('selectiondata',this.selectiondata)
        },
        onCheckSelectChange: (selection) => {
          // this.onCheckSelectChange1(selection)
        }
      },

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: ()=>this.openChoose(),
          text: '备件选择',
          position: 'left',
          isShow: true
        },
        {
          compKey: 'button2',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => this.del(),
          text: '备件删除',
          position: 'left',
          isShow: true
        },
        {
          compKey: 'button4',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => this.preserve(),
          text: '出库',
          position: 'right',
          isShow: true
        },
        {
          compKey: 'button5',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => {
            for (const attr in this.formField) {
              if (attr !== 'applyOrderCode') {
                this.formField[attr] = ''
              }
            }
          },
          text: '重置',
          position: 'right',
          isShow: true
        }
      ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partNo',
              label: '备件编码',
              align: 'center'
            },
            {
              prop: 'partName',
              label: '备件名称',
              align: 'center'
            },
            {
              prop: 'warehouseName',
              label: '仓位名称',
              align: 'center'
            },
            {
              prop: 'pointPriceTax', 
              label: '单价',
              align: 'center'
            },
            {
              prop: 'dlrShortName',
              label: '备件单位',
              align: 'center'
            },
            {
              prop: 'availableInventory',
              label: '理论可用库存',
              align: 'center'
            },
            {
              prop: 'outStoreQty',
              label: '申请数量+',
              align: 'center',
              isSlot: true
            }
          ]
    }
  },
  methods: {
    saleQtyChange(val, scope) {
      if (!val) return this.$message('数量不能为空!')
      const reg = /c|(^[0-9]+$)/
      if (!reg.test(val)) {
        this.$message('请输入正确的数量!')
        scope.row['outStoreQty'] = ''
      }
    },
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    // 删除
    del() {
      this.selectiondata.forEach((element) => {
        this.$refs['multipleTable'].list.forEach((item) => {
          if (element == item) {
            this.$refs['multipleTable'].list.splice(item, 1)
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            })
          }
        })
      })
    },
    // 备件选择
    selectiondata1(selectiondata) {
        this.$refs['multipleTable'].list = selectiondata
    },
    openChoose(){
        if(!this.$refs['multipleTable'].list.length){
            this.chosenList = this.$refs['multipleTable'].list
        }        
        this.$refs['addcollect'].isViewPopWindowsAdd = true
    },
    // 保存
    preserve() {
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return
      let isValid = true
      this.$refs['multipleTable'].list.every(row => {
        if (!row['outStoreQty']) {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid) return this.$message('网格中[ 申请数量+ ]为必填！')
      // 如果有必填项没有填，这两行代码就会拦截 不往下执行代码
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: vehiclePdiPriceInquirys.interiorOutStorage,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          ...this.formField,
          applyOrderId: this.EditRowData.applyOrderId,
          otherOutboundDList: this.$refs['multipleTable'].list
        }
      }
      console.log('queryObj',queryObj)
    //   return
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.formField.applyPerson = null 
          this.formField.receivePerson = null 
          this.$refs['multipleTable'].list = []
        } else {
          // 保存失败
          this.$message({
            message: '保存失败',
            type: 'warn',
            uration: 2000
          })
        }
      })
    }
  }
}
</script>
<style scoped>
/*.formBoxContain {*/
/*  height: 600px;*/
/*}*/
</style>
